#!/usr/bin/python3
# coding:utf-8

import os
import sys
import subprocess

#  输入包名、APP版本号，Git版本号，渠道
# 提供trace.txt 然后输出到窗口


package_name = sys.argv[1]
apk_channel = sys.argv[2]
apk_version = sys.argv[3]
git_version = sys.argv[4]
stack_file = sys.argv[5]

print ('>>>>>>>> 应用包名：', package_name)
print ('>>>>>>>> 应用渠道：', apk_channel)
print ('>>>>>>>> 应用版本：', apk_version)
print ('>>>>>>>> 代码版本：', git_version)
print ('>>>>>>>> 堆栈文件：', stack_file)

file_name = "{}-{}-{}-{}".format(package_name, apk_channel, apk_version, git_version)

os.system("rm -rf ./build")
os.system("mkdir ./build")

print ('>>>>>>>> 开始下载混淆文件...')


cmd_download = "curl -s -u admin:Tange@2021  -L -X 'GET' 'http://repo-sdk.tange-ai.com/service/rest/v1/search/assets/download?sort=version&direction=desc&group=com.tange.ai.mapping&name={}.{}&maven.baseVersion={}.{}-SNAPSHOT&maven.extension=zip' -o ./build/{}.zip".format(package_name, apk_channel, apk_version, git_version, file_name)

print ('>>>>>>>> 下载命令为 ' + cmd_download)

result_download = os.system(cmd_download)
if result_download != 0:
    print(">>>>>>>> 下载混淆文件失败") 
    sys.exit(-1)

whole_file_path = "./build/{}.zip".format(file_name)
if os.path.exists(whole_file_path):
    print(">>>>>>>> 下载混淆文件成功")
else:
    print(">>>>>>>> 下载混淆文件失败！")
    sys.exit(-1)

cmd_unzip = "unzip -q ./build/{}.zip -d ./build/{}".format(file_name, file_name)
result_unzip = os.system(cmd_unzip)
if result_unzip != 0:
    print(">>>>>>>> 解压混淆文件失败") 
    sys.exit(-1)

print(">>>>>>>> 解压混淆文件成功") 

print(">>>>>>>> 反混淆后的堆栈：\n") 

cmd_retrace = "./tools/retrace/bin/retrace ./build/{}/fullRelease/mapping.txt {}".format(file_name, stack_file)    
os.system(cmd_retrace)

